import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app/common/global.dart';
import 'package:flutter_app/model/tweet.dart';
import 'package:flutter_app/style/color.dart';
import 'package:flutter_app/tools/http.dart';
import 'package:flutter_app/view/tweet/reply_item.dart';
import 'package:flutter_app/view/tweet/tweet_grid_item.dart';
import 'package:flutter_app/view/dialog/toast.dart';
import 'package:flutter_app/view/dialog/user_info_dialog.dart';
import 'package:flutter_app/tools/utils.dart';
import 'package:flutter_app/tools/widget.dart';
import 'package:http/http.dart' as http;

GlobalKey<FormState> formKey = GlobalKey<FormState>();

class TweetDetails extends StatefulWidget {
  final TweetGridItem tweetGridItem;

  TweetDetails(this.tweetGridItem, {Key key}) : super(key: key);

  @override
  _TweetDetailsState createState() => _TweetDetailsState();
}

class _TweetDetailsState extends State<TweetDetails> {
  List<Reply> replyList = [];
  int p = 0;
  String refreshTime; //刷新时间
  bool noMore = false; //没有更多
  bool isLoading = false; //是否正在加载数据

  ScrollController _controller = new ScrollController(); //上拉加载更多控制器
  TextEditingController _textController = new TextEditingController(); //回复框控制器
  GlobalKey<RefreshIndicatorState> _indicatorKey =
      GlobalKey<RefreshIndicatorState>(); //控制下拉刷新

  bool maskVisible = false; //蒙版
  FocusNode _focusNode = FocusNode();

  Reply reply;

  @override
  void initState() {
    super.initState();

    reply = Reply(tweetId: widget.tweetGridItem.tweet.id);

    _onRefresh();

    //输入框焦点
    _focusNode.addListener(() {
      if (_focusNode.hasFocus) {
        maskVisible = true;
        setState(() {});
      } else {
        maskVisible = false;
        setState(() {});
      }
    });
  }

  issueReply() {
    if (reply.text.length == 0) {
      showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            title: Text("提示"),
            content: Text("至少说点什么吧。"),
          );
        },
      );
      return;
    }
    m_http.issueReply(reply).then((value) async {
      if (value == "ok") {
        _textController.clear();
        removeTextFieldFocus();

        Toast.toast(context, msg: "发送成功~", showTime: 2500);
        await Future.delayed(Duration(milliseconds: 2500), () {
          setState(() {
            widget.tweetGridItem.tweet.repliesCount += 1;
          });
        });
        if (_controller.position.pixels > 0) {
          _controller.jumpTo(0);
        } else {
          _indicatorKey.currentState.show();
        }
      }
    });
  }

//获取回复列表根据tweetId和页号
  getReplyList() async {
    if (!isLoading) {
      isLoading = true;
      p += 1;
      if (p == 1) {
        refreshTime = m_utils.formartDateTimeToSecond(DateTime.now());
        replyList = [];
        noMore = false;
      }
      if (!noMore) {
        http.Response response = await http.get(Global.serversUrl +
            "/ReplyList?userId=${Global.userId}&tweetId=${widget.tweetGridItem.tweet.id}&p=$p&refreshTime=" +
            refreshTime);
        List<dynamic> reultReplyList = json.decode(response.body);
        if (reultReplyList.length > 0) {
          for (dynamic reultReply in reultReplyList) {
            replyList.add(Reply.fromJson(reultReply));
          }
        } else {
          noMore = true;
        }
      }
      isLoading = false;
    }
    if (mounted) {
      setState(() {});
    }
  }

//下拉重新刷新
  Future<Null> _onRefresh() async {
    p = 0;
    await getReplyList();
    await Future.delayed(Duration(milliseconds: 800), () {});
  }

  Widget getRow(Reply reply) {
    return new ReplyItem(
      reply: reply,
      key: UniqueKey(), //必须要有key 不然setState时listView可能不刷新
    );
  }

//后退到上一页
  _backToPreviousPage() {
    widget.tweetGridItem.isDetailPage = false;
    Navigator.of(context).pop(widget.tweetGridItem);
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        _backToPreviousPage();
        return true;
      },
      child: Scaffold(
          appBar: AppBar(
            backgroundColor: m_color.black,
            leading: IconButton(
              padding: EdgeInsets.fromLTRB(0, 0, 10, 0),
              alignment: Alignment.centerRight,
              icon: (Icon(Icons.arrow_back)),
              onPressed: _backToPreviousPage,
            ),
          ),
          //body占屏幕的大部分
          body: Container(
              decoration: BoxDecoration(color: Color(0x33EEEEEE)),
              child: Column(
                children: [
                  Expanded(
                      child: Scrollbar(
                          child: Stack(children: [
                    RefreshIndicator(
                      key: _indicatorKey,
                      child: ListView.builder(
                        scrollDirection: Axis.vertical,
                        shrinkWrap: true, //仅包含内容长度
                        physics: AlwaysScrollableScrollPhysics(),

                        itemCount: replyList.length * 2 + 3,
                        itemBuilder: (BuildContext context, int position) {
                          if (position == 0) {
                            return Padding(
                              key: UniqueKey(),
                              padding: EdgeInsets.all(3.0),
                              child: widget.tweetGridItem,
                            );
                          }

                          if (position < replyList.length * 2 + 2) {
                            if (position % 2 == 1) {
                              return Divider(height: 3);
                            } else {
                              return getRow(
                                  replyList[(position - 2) ~/ 2]); //~/(取整)
                            }
                          } else {
                            if (_controller.position.haveDimensions &&
                                !_controller.position.outOfRange &&
                                !noMore) {
                              Future.delayed(Duration(milliseconds: 200))
                                  .then((e) {
                                getReplyList();
                              });
                            }
                            return utilsWidget.loadingWidget(isLoading, noMore);
                          }
                        },
                        controller: _controller,
                      ),
                      onRefresh: _onRefresh,
                    ),
                    //点击输入框时出现的阴影蒙版
                    Positioned(
                        top: 0,
                        left: 0,
                        right: 0,
                        bottom: 0,
                        child: Visibility(
                            visible: maskVisible,
                            maintainInteractivity: false,
                            child: InkWell(
                              child: Container(
                                decoration: new BoxDecoration(
                                  color: Colors.black54,
                                ),
                              ),
                              onTap: removeTextFieldFocus,
                            )))
                  ]))),
                  Divider(height: 1.0),
                  Container(
                      decoration: BoxDecoration(color: Color(0xFFFFFFFF)),
                      child: Padding(
                        padding: EdgeInsets.fromLTRB(15, 5, 15, 5),
                        child: Row(children: [
                          //回复输入框
                          Expanded(
                              child: TextFormField(
                            key: formKey,
                            controller: _textController,
                            focusNode: _focusNode,
                            style: TextStyle(fontSize: 16),
                            decoration: new InputDecoration(
                              isCollapsed:
                                  true, //重点，相当于高度包裹的意思，必须设置为true，不然有默认奇妙的最小高度
                              contentPadding: EdgeInsets.symmetric(
                                  horizontal: 8, vertical: 4), //内容内边距，影响高度
                              hintText: '说点什么吧.',
                            ),
                            maxLines: 5,
                            minLines: 1,
                            onChanged: (value) {
                              reply.text = value ?? "";
                            },
                          )),

                          //用户名设置
                          Container(
                            margin: EdgeInsets.fromLTRB(10, 0, 10, 0),
                            child: InkWell(
                              child: SizedBox(
                                child: Icon(
                                  Icons.account_circle,
                                  color: m_color.grey,
                                  size: 24,
                                ),
                              ),
                              onTap: () {
                                //显示 dialog
                                showDialog(
                                  context: context,
                                  barrierDismissible: true, //点击dialog外部 是否可以销毁
                                  builder: (BuildContext context) {
                                    return UserInfoDialog();
                                  },
                                ).then((value) => setState(() {}));
                              },
                            ),
                          ),
                          //发送回复
                          InkWell(
                              child: SizedBox(
                                child: Icon(
                                  Icons.send,
                                  color: m_color.grey,
                                  size: 24,
                                ),
                              ),
                              onTap: issueReply),
                        ]),
                      ))
                ],
              ))),
    );
  }

  @override
  void dispose() {
    _focusNode.dispose();
    super.dispose();
  }

  removeTextFieldFocus() {
    FocusScope.of(context).requestFocus(FocusNode());
    maskVisible = false;
    setState(() {});
  }
}
